import React, {Component} from 'react';
import './Map.scss'
import NavHeader from "../../components/NavHeader/NavHeader";
import styles from './index.module.css'
import {require} from "../../netWork";
import {Link} from "react-router-dom";
// import {baseUrl} from "../../utiles/baseUrl";
import {Toast} from "antd-mobile";
import HouseItem from "../../components/HoustItem/HouseItem";
//圆形覆盖物样式
const titleStyle = {
    cursor: 'pointer',
    border: '0px solid rgb(255,0,0)',
    padding: '0px',
    whiteSpace: '12px',
    color: 'rgb(255,255,25,)',
    textAlign: 'center'
};


class Map extends Component {
    state = {
        houseList:[],
        isShowList:false
    }
    componentDidMount() {
        this.initMap()
    }
    //初始化地图
    initMap = () =>{
        let {label, value} = JSON.parse(localStorage.getItem('hkzf'));
        //全局对象使用window调用
        var map = new window.BMapGL.Map("container");
        //能够在其他方法中获取map实例
        this.map = map;
        //开启滑轮缩放
        map.enableScrollWheelZoom(true);
        var scaleCtrl = new window.BMapGL.ScaleControl();  // 添加比例尺控件
        map.addControl(scaleCtrl);
        var zoomCtrl = new window.BMapGL.ZoomControl();  // 添加缩放控件
        map.addControl(zoomCtrl);
        //设置中心坐标
        var point = new window.BMapGL.Point(116.404, 39.915);
        //绘制地图
        map.centerAndZoom(point, 10);

        //根据经纬度重绘地图
        var myGeo = new window.BMapGL.Geocoder();
        // 将地址解析结果显示在地图上，并调整地图视野 label:当前城市
        myGeo.getPoint(label, async (point) => {
            if (point) {
                // //重绘地图
                map.centerAndZoom(point, 10);
                map.addOverlay(new window.BMapGL.Marker(point, {title: label}));
                //调用渲染覆盖物
                this.renderOverlays(value)
            } else {
                alert('您选择的地址没有解析到结果！');
            }
            // 获取区内数据
        }, label);
        map.addEventListener('movestart',() =>{
            if(this.state.isShowList){
                this.setState({
                    isShowList:false
                })
            }
        })
    };

    /*渲染覆盖物入口
    * 1.接受id参数
    * 2.获取房源类型以及下及地图缩放级别*/
    renderOverlays = async (id) =>{
        Toast.loading('加载中', 0)
       await require({
            url:'/area/map',
            data:{id}
        }).then(res =>{
            Toast.hide()
           //获取覆盖物类型和缩放级别
           const {type,nextZoom} = this.getTypeAanZoom();
           const data = res.body;
           // console.log(res);
           data.forEach(item =>{
               //创建覆盖物
               this.createOverlays(item,type,nextZoom)
           })
        })

    };

    /*  计算覆盖物类型和缩放级别*/
    getTypeAanZoom = () =>{
    const zoom = this.map.getZoom();
    let type,nextZoom;
    if(zoom >= 9 && zoom < 13){
        //区
        type = 'circle';
        nextZoom = 13
    }else if(zoom >= 13 && zoom < 14){
        //镇
        nextZoom = 14;
        type = 'circle'
    }else if(zoom >= 14 && zoom < 17){
        // 小区
        nextZoom = 16;
        type = "rect"
    }
        return {type,nextZoom}
    };

    /*创建覆盖物*/
    createOverlays = (data,type,nextZoom) =>{
        const {coord: {latitude, longitude}, label: areaName,count,value} = data;
        const areaSite =  new window.BMapGL.Point(longitude, latitude);
        if(type === 'circle'){
            //创建圆形覆盖物
            this.createCircle(areaSite,areaName,count,nextZoom,value)
        }else {
            //创建矩形覆盖物
            this.createRect(areaSite,areaName,count,value)
        }

    };
    //创建圆形覆盖物
    createCircle = (areaSite,areaName,count,nextZoom,value) =>{
        var title = new window.BMapGL.Label('', {       // 创建文本标注
            position: areaSite,
            //偏移量
            offset: new window.BMapGL.Size(-35, -35)
        });
        //用于获取区下的房屋数据
        title.id = value;
        title.setContent(`
                <div class="${styles.bubble}">
                   <p>${count}</p>
                   <p class="${styles.name}">${areaName}</p>
                </div>`);
        this.map.addOverlay(title);    // 将标注添加到地图中
        title.setStyle(titleStyle);
        title.addEventListener('click', () => {    this.renderOverlays(value);
            // new window.BMapGL.Point(areaSite);
            this.map.centerAndZoom(areaSite, nextZoom);

            //清除覆盖物
            this.map.clearOverlays()
        });
        title.setStyle({                              // 设置label的样式
            color: '#000',
            fontSize: '15px',
            border: '2px solid #1E90FF'
        })
    };
    //创建矩形覆盖物
    createRect = (areaSite,areaName,count,value) =>{
        var title = new window.BMapGL.Label('', {       // 创建文本标注
            position: areaSite,
            //偏移量
            offset: new window.BMapGL.Size(-50, -29)
        });
        //用于获取区下的房屋数据
        title.id = value;
        title.setContent(`
                <div class="${styles.rect}">
                   <span class="${styles.housename}">${areaName}</span>
                   <span class="${styles.housenum}">${count}</span>
                   <i class="${styles.arrow}"></i>
                </div>`);
        this.map.addOverlay(title);    // 将标注添加到地图中
        title.setStyle(titleStyle);
        title.addEventListener('click', (e) => {

            // console.log('小区覆盖物');
            this.getHouseList(value);
            // console.log(e);
            // const target = e.currentTarget.latLng
            // console.log(target);
            // this.map.panBy(window.innerWidth / 2 - target.lng,(window.innerHeight-300)/2 - target.lat)

        });
        title.setStyle({                              // 设置label的样式
            color: '#000',
            fontSize: '15px',
            border: '2px solid #1E90FF'
        })
    };

    //获取小区数据
     getHouseList =async (id) =>{
         Toast.loading('加载中',0)
       await  require({
             url:'/houses',
             data:{id}
         }).then(res =>{
           this.setState({
               houseList:res.body.list,
               isShowList:true
           })
         })
         Toast.hide()
     };


    render() {
        return (
            <div className='f-map'>
                <div className='na-map'>
                    <NavHeader>地图找房</NavHeader>
                </div>
                <div id="container"/>
                {/*房源列表*/}
                <div className={[styles.houseList,this.state.isShowList ? styles.show : ' '].join(' ')}>
                    <div className={styles.titleWrap}>
                      <h1 className={styles.listTitle}>房屋列表</h1>
                        <Link className={styles.titleMore} to='/home/list'>
                            更多房源
                        </Link>
                    </div>
                        {/*<div className={styles.houseItems} >
                            房屋结构
                            {
                                this.state.houseList.map(item =>{
                                    return  <div className={styles.house} key={item.houseCode}>
                                        <div className={styles.imgWrap}>
                                            <img className={styles.img} src={baseUrl+item.houseImg} alt=""/>
                                        </div>
                                        <div className={styles.content}>
                                            <h3 className={styles.title}>
                                                {item.title}
                                            </h3>
                                            <div className={styles.desc}>
                                                {item.desc}
                                            </div>
                                            <div>
                                          {item.tags.map(tag =>{
                                                 return    <span key={tag} className={[styles.tag,styles.tag1].join(' ')}>{tag}</span>
                                                })}
                                            </div>
                                            <div className={styles.price}>
                                                <span className={styles.priceNum}>{item.price}</span>元/月
                                            </div>
                                        </div>
                                    </div>
                                })
                            }
                        </div>*/}
                    <HouseItem houseList={this.state.houseList}/>
                </div>
            </div>

        );
    }
}

export default Map;
